package com.sf.dlb.utils;

import com.sf.dlb.jpa.model.TokenEntity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Token 缓存
 * Created by tanjing on 2018/12/10.
 */
public class TokenCache {

    private static final String ACTIVE_LIST_KEY="user_token";

    /**
     * 获取Token列表
     * @return
     */
    public static List<TokenEntity> getActiveTokenEntityList(){
        return (List<TokenEntity>)CacheUtils.get(ACTIVE_LIST_KEY);
    }
    /**
     * 获取token对象
     * @param code
     * @return
     */
    public static TokenEntity getTokenEntityByToken(String code){
        return (TokenEntity) CacheUtils.get(code);
    }
    /**
     * 获取用户名
     * @param code
     * @return
     */
    public static String getUserIdByToken(String code){
        TokenEntity token = getTokenEntityByToken(code);
        if(token == null){
            return null;
        }
        return token.getUserId();
    }
    /**
     * 放入缓存
     * @param token
     */
    public static void tokenPut(TokenEntity token) {
        CacheUtils.put(token.getToken(), token);
        List<TokenEntity> activeList = getActiveTokenEntityList();
        if(activeList == null) {
            activeList = new ArrayList<>();
        }
        activeList.add(token);
        CacheUtils.put(ACTIVE_LIST_KEY, activeList);
    }
    /**
     * 刷新缓存（清理失效token）
     */
    public void refreshCache() throws Exception {
        List<TokenEntity> all = getActiveTokenEntityList();

        List<TokenEntity> invalidList = new ArrayList<TokenEntity>();
        Date current = new Date();
        for(TokenEntity p: all){
            long pass = (current.getTime()-p.getCreateDate().getTime())/1000;	//转化秒
            if(pass > p.getExpiresIn()) {
                invalidList.add(p);
                CacheUtils.remove(p.getToken());
            }
        }
        all.removeAll(invalidList);
        CacheUtils.put(ACTIVE_LIST_KEY, all);
    }
}
